package org.example2;

import java.io.*;
import java.util.Arrays;

/**
 *   -Dfile.encoding=utf-8
 *   -Dfile.encoding=gbk
 *
 *   FileReader 采取本地默认字符,在windows中使用的是gbk,
 *                      linux中默认的是utf-8.但我们可以通过 -Dfile.encoding来手动指定
 *                      idea中默认是utf-8
 */

public class AppOutputStreamReader {
    static String encodingGbk = "gbk";
    static String encodingUtf8 = "utf-8";

    static String fileGbk = "fileGbk.txt";
    static String fileUtf8 = "fileUtf8.txt";
    static String path = getPath();


    public static void main(String[] args) throws Exception {
        writeFiles();

        readFiles();


    }

    private static void readFiles() throws Exception {

//        System.out.println(path+fileGbk);
//        System.out.println(path+fileUtf8);
        FileReader fileReaderGbk = new FileReader(path + fileGbk);
        FileReader fileReaderUft8 = new FileReader(path + fileUtf8);
//        InputStreamReader fileReaderGbk = new InputStreamReader(new FileInputStream(path+fileGbk),"gbk");
//        InputStreamReader fileReaderUft8 = new InputStreamReader(new FileInputStream(path+fileUtf8),"utf-8");

        char[] bufferGbk = new char[1024];
        int lenGbk = 0;
        while (  ( lenGbk = fileReaderGbk.read(bufferGbk) ) != -1) {
            System.out.println("lenGbk is "+lenGbk);
            printPart(bufferGbk,lenGbk);
        }

        System.out.println("--------上面gbk,下面uft8----------");

        char[] bufferUtf8 = new char[1024];
        int lenUft8 = 0;
        while (  ( lenUft8 = fileReaderUft8.read(bufferUtf8) ) != -1) {
            System.out.println("lenUft8 is "+lenUft8);
            printPart(bufferUtf8,lenUft8);
        }


        fileReaderGbk.close();
        fileReaderUft8.close();
    }

    private static void printPart(char[] buffer, int partLen) {
        char[] chars = new char[partLen];
        for (int i = 0; i <partLen ; i++) {
            chars[i] = buffer[i];
        }

        System.out.println(Arrays.toString(chars));
    }

    public static void writeFiles() throws Exception {
        String content = "我爱你";


        OutputStreamWriter oswGbk = new OutputStreamWriter(new FileOutputStream(path + fileGbk), encodingGbk);
        OutputStreamWriter oswUtf8 = new OutputStreamWriter(new FileOutputStream(path + fileUtf8), encodingUtf8);

        oswGbk.write(content);
        oswUtf8.write(content);

        oswGbk.close();
        oswUtf8.close();

        System.out.println("文件已写在:" + path);
    }

    public static String getPath() {
//        path = AppOutputStreamReader.class.getResource("").getPath();

        path = System.getProperty("user.dir") +"/io/target/";
        return path;
    }
}

